package com.xhwl.data.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhwl.common.dto.cent.sdata.BuildingDTO;
import com.xhwl.common.dto.cent.sdata.FloorDTO;
import com.xhwl.common.dto.cent.sdata.PublicAreaDTO;
import com.xhwl.common.dto.cent.sdata.SpaceFunctionTypeDTO;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.OrganizationType;
import com.xhwl.common.pojo.cent.sdata.PublicArea;
import com.xhwl.common.pojo.cent.sdata.SpaceFunctionType;
import com.xhwl.common.query.cent.sdata.PublicAreaQuery;
import com.xhwl.common.query.cent.sdata.SpaceFunctionTypeQuery;
import com.xhwl.common.utils.StringUtils;
import com.xhwl.data.service.IOrganizationTypeService;
import com.xhwl.data.service.IPublicAreaService;
import com.xhwl.data.service.ISpaceFunctionTypeService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: luyi
 * @Description:
 * @Date: Create in 15:56 2021/4/15
 */
@RestController
public class PublicAreaController {

    @Autowired
    private IPublicAreaService publicAreaService;

    @Autowired
    private ISpaceFunctionTypeService spaceFunctionTypeService;

    @Autowired
    private IOrganizationTypeService organizationTypeService;

    private static final Logger log = LoggerFactory.getLogger(PublicAreaController.class);

    @RequestMapping(value = "/public-area/batch-create")
    public ResultJson batchCreate(@RequestBody List<PublicAreaDTO> publicAreaDTOs) {
        if (CollectionUtils.isEmpty(publicAreaDTOs)) {
            return ResultJson.success();
        }
        long count = publicAreaDTOs.stream().map(PublicAreaDTO::getCode).distinct().count();
        if (publicAreaDTOs.size() > count) {
            return ResultJson.fail("编码重复");
        }
        for (PublicAreaDTO publicAreaDTO : publicAreaDTOs) {
            if (StringUtils.isEmpty(publicAreaDTO.getName()) || publicAreaDTO.getName().length() > 32) {
                return ResultJson.fail("名称输入错误");
            }
            if (StringUtils.isNotEmpty(publicAreaDTO.getCode()) && publicAreaDTO.getCode().length() > 36) {
                return ResultJson.fail("编码输入错误");
            }
            if (null == publicAreaDTO.getParentId() || publicAreaDTO.getParentId().toString().length() > 11) {
                return ResultJson.fail("上级信息错误");
            }
        }
        return publicAreaService.batchCreate(publicAreaDTOs);
    }

    @RequestMapping(value = "/public-area/create")
    public ResultJson create(@RequestBody PublicAreaDTO publicAreaDTO) {
        if (null == publicAreaDTO) {
            return ResultJson.fail("参数错误");
        }
        if (StringUtils.isEmpty(publicAreaDTO.getName()) || publicAreaDTO.getName().length() > 32) {
            return ResultJson.fail("名称输入错误");
        }
        if (StringUtils.isNotEmpty(publicAreaDTO.getCode()) && publicAreaDTO.getCode().length() > 36) {
            return ResultJson.fail("编码输入错误");
        }
        if (null == publicAreaDTO.getParentId() || publicAreaDTO.getParentId().toString().length() > 11) {
            return ResultJson.fail("上级信息错误");
        }

        if (null != publicAreaDTO.getId()) {
            return publicAreaService.update(publicAreaDTO);
        } else {
            if (null == publicAreaDTO.getParentId()) {
                return ResultJson.fail("参数错误");
            }
            return publicAreaService.create(publicAreaDTO);
        }

    }

    @RequestMapping(value = "/public-area/list")
    public ResultJson list(@RequestBody PublicAreaQuery publicAreaQuery) {
        List<PublicArea> list = publicAreaService.list(publicAreaQuery);
        return ResultJson.success(list);
    }

    @RequestMapping(value = "/public-area/page")
    public ResultJson page(@RequestBody PublicAreaQuery publicAreaQuery, Page page) {
        Page<PublicArea> page1 = publicAreaService.page(publicAreaQuery, page);
        return ResultJson.success(toDTO(page1,publicAreaQuery.getTypeId()));
    }

    @RequestMapping(value = "/public-area/delete")
    public ResultJson delete(Integer id) {
        return publicAreaService.delete(id);
    }

    @RequestMapping(value = "/public-area/detail")
    public ResultJson detail(Integer id, Integer orgId,Integer typeId) {
        QueryWrapper<PublicArea> publicAreaQueryWrapper = new QueryWrapper<>();
        if (null != id) {
            publicAreaQueryWrapper.eq("id", id);
        } else if (null != orgId) {
            publicAreaQueryWrapper.eq("organization_id", orgId);
        } else {
            return ResultJson.success();
        }
        PublicArea one = publicAreaService.getOne(publicAreaQueryWrapper);
        if (null == one) {
            log.warn("公区数据不存在");
            return ResultJson.success();
        }
        List<SpaceFunctionType> spaceFunctionTypes = listFunctionType();
        PublicAreaDTO publicAreaDTO = processBean(one, spaceFunctionTypes,typeId);
        return ResultJson.success(publicAreaDTO);
    }

    /**
     * 获取当前编码
     *
     * @return
     */
    @GetMapping("/public-area/get-current-code")
    public ResultJson getCurrentCode() {
        return ResultJson.success().setResult(publicAreaService.getCurrentCode());
    }

    private Page toDTO(Page publicAreaPage,Integer typeId) {
        if (CollectionUtils.isEmpty(publicAreaPage.getRecords())) {
            return publicAreaPage;
        }
        List<PublicArea> records = publicAreaPage.getRecords();
        List<SpaceFunctionType> spaceFunctionTypes = listFunctionType();
        List<PublicAreaDTO> publicAreaDTOS = records.stream()
                .map(r -> processBean(r, spaceFunctionTypes,typeId)
                ).collect(Collectors.toList());
        return publicAreaPage.setRecords(publicAreaDTOS);
    }

    private PublicAreaDTO processBean(PublicArea publicArea, List<SpaceFunctionType> spaceFunctionTypes,Integer typeId) {
        PublicAreaDTO publicAreaDTO = new PublicAreaDTO();
        BeanUtils.copyProperties(publicArea, publicAreaDTO);
        //填充功能名称
        if (null != publicAreaDTO.getFunctionType()) {
            for (SpaceFunctionType spaceFunctionType : spaceFunctionTypes) {
                if (spaceFunctionType.getId().equals(publicAreaDTO.getFunctionType())) {
                    publicAreaDTO.setFunctionName(spaceFunctionType.getName());
                    break;
                }
            }
        }
        dealJson (publicAreaDTO,typeId);
        return publicAreaDTO;
    }

    /**
     * 兼容历史数据
     */
    private void dealJson (PublicArea param,Integer typeId){
        if(typeId == null){
            return;
        }
        QueryWrapper<OrganizationType> organizationTypeQueryWrapper = new QueryWrapper<>();
        organizationTypeQueryWrapper.eq("id", typeId);
        OrganizationType organizationType = organizationTypeService.getOne(organizationTypeQueryWrapper);
        String source = organizationType.getSource();
        if(org.apache.commons.lang3.StringUtils.isEmpty(source)){
            return;
        }
        Map<String,Object> map = new HashMap<>();
        JSONObject sourceJson = JSON.parseObject(source);
        JSONArray fields = sourceJson.getJSONArray("fields");
        if(CollectionUtil.isNotEmpty(fields)) {
            for (int i = 0; i < fields.size(); i++) {
                JSONObject fieldJsonObject = fields.getJSONObject(i);
                fieldJsonObject.remove("__config__");
                String vModel = fieldJsonObject.getString("vModel");
                //兼容以前数据
                if ("name".equals(vModel)) {
                    fields.getJSONObject(i).put("defaultValue",param.getName() != null ? param.getName() : "");
                    map.put("name",param.getName() != null ? param.getName() : "");
                } else if ("code".equals(vModel)) {
                    fields.getJSONObject(i).put("defaultValue",param.getCode() != null ? param.getCode() : "");
                    map.put("code",param.getCode() != null ? param.getCode() : "");
                } else if ("sortField".equals(vModel)){
                    fields.getJSONObject(i).put("defaultValue",param.getSortField() != null ? param.getSortField() : "");
                    map.put("sortField",param.getSortField() != null ? param.getSortField() : "");
                } else {
                    if(param.getExpand() != null) {
                        JSONObject jsonObject = JSON.parseObject(param.getExpand());
                        if(jsonObject.get(vModel) != null) {
                            fields.getJSONObject(i).put("defaultValue", jsonObject.get(vModel));
                            map.put(vModel,jsonObject.get(vModel));
                        }else{
                            map.put(vModel,"");
                        }
                    }else{
                        map.put(vModel,"");
                    }
                }
            }
        }
        param.setExpand(JSON.toJSONString(sourceJson));
        param.setFullData(JSON.toJSONString(map));
    }

    private List<SpaceFunctionType> listFunctionType() {
        return spaceFunctionTypeService.list(new QueryWrapper<SpaceFunctionType>()
                .eq("org_type", OrganizationTypeEnum.PUBLIC_AREA.getId()));
    }
}
